package com.leen.service.impl;

import com.leen.common.util.StringUtils;
import com.leen.common.vo.ResponseVO;
import com.leen.dto.RoleDTO;
import com.leen.entity.Role;
import com.leen.repository.RoleRepository;
import com.leen.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色业务逻辑
 *
 * @author admin
 * @date 2021-04-21
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class RoleServiceImpl extends CurdServiceImpl<Role,Integer> implements RoleService {

    private RoleRepository roleRepository;

    @Autowired
    public void setRoleRepository(RoleRepository roleRepository) {
        this.roleRepository = roleRepository;
        super.setCrudRepository(roleRepository);
    }


    @Override
    public ResponseVO search(RoleDTO roleDTO) {
        Pageable pageable= PageRequest.of(roleDTO.getPageNumber()-1, roleDTO.getPageSize());

        Specification<Role> specification=new Specification<Role>() {
            @Override
            public Predicate toPredicate(Root<Role> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {

                List<Predicate> arr=new ArrayList<>();

                arr.add(criteriaBuilder.equal(root.get("status"),roleDTO.getStatus()));

                if(StringUtils.isNotBlank(roleDTO.getRoleName())){
                    arr.add(criteriaBuilder.like(root.get("roleName"),"%" +roleDTO.getRoleName()+"%"));
                }

                return criteriaBuilder.and(arr.toArray(new Predicate[arr.size()]));
            }
        };

        Page<Role> page = this.roleRepository.findAll(specification, pageable);

        return new ResponseVO(page.getTotalElements(),page.getContent());
    }
}
